import { Application } from "mydog";
import { IUidSid } from "../definition/interface";

export class GameLogic {

  protected app: Application;
  protected roomId: number;
  protected users: Array<IUidSid>;

  constructor(app: Application, roomId: number, users: Array<IUidSid>) {
    this.app = app;
    this.roomId = roomId;
    this.users = users;
  }

  // user
  protected getUserByUid(uid: number) {
    for (const user of this.users) {
      if (user.uid === uid) {
        return user;
      }
    }
    return null;
  }

  protected getAllUsersExceptUid(uid: number) {
    let users: Array<IUidSid> = [];
    for (const user of this.users) {
      if (user.uid !== uid) {
        users.push(user);
      }
    }
    return users;
  }

  // message
  public sendMessageToUid(route: number, uid: number, msg: any) {
    const user = this.getUserByUid(uid);
    if (!!user) {
      this.app.sendMsgByUidSid(route, msg, [user]);
    }
  }

  public sendMessageToAll(route: number, msg: any) {
    this.app.sendMsgByUidSid(route, msg, this.users);
  }

  public sendMessageToAllExceptUid(route: number, uid: number, msg: any) {
    const uidsid = this.getAllUsersExceptUid(uid);
    this.app.sendMsgByUidSid(route, msg, uidsid);
  }
}
